﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Controls;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Notification;
using Microsoft.Phone.Shell;
using SurfaceAd.SDK.WP;

namespace ComicIsland.App
{
    public partial class IndexPage : PhoneApplicationPage
    {
        private bool IsLoadedCategorySpecial = false;
        private bool IsLoaded_SearchChannel_CategoryChoice = false, IsLoaded_SearchChannel_HotSearchword = false;
        private DispatcherTimer refreshTimerBookStoreFocus;
        private const int TIMER_INTERVAL = 5;//秒
        private int currentSelectedIndexJsonBookStoreFocusAdlistjson = 0;
        private JsonBookStoreFocusAdlistjson currentSelectedItemJsonBookStoreFocusAdlistjson = null;
        //书架栏目
        private bool IsLoaded_BookcaseChannel_Empty = false, IsNeedLoadBookcase = false;
        private int IsConfirmExist = -1;
        public IndexPage()
        {
            InitializeComponent();
            this.IsNeedLoadBookcase = true;
            //
            //
            System.Threading.Tasks.Task.Run(() =>
            {
                this.LoadHotComic();
                this.InitPushNotificationChannel();
                //
                this.GetComicsUpdateInfo();
            });
            //
            LoadBookStoreFocus();
            LoadBookStoreAlbum();

        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //
            Task.Run(() => { this.LoadBookcase(); });

        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            IsNeedLoadBookcase = false;
            //
            if (this.llsCategorySubject != null)//选择项不置空，返回后再点击原来的选项就不响应了
                this.llsCategorySubject.SelectedItem = null;
            if (this.llsCategorySpecial != null)
                this.llsCategorySpecial.SelectedItem = null;
            if (this.llsCategoryAuthor != null)
                this.llsCategoryAuthor.SelectedItem = null;
            //
            this.IsRefreshAlbum = false;
            this.IsRefreshFocus = false;
            //
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (this.pivotStore == this.pivot.SelectedItem)
            {
                IsConfirmExist++;
                Action show = delegate()
                {
                    //3秒内未再次按backkeypress则表示不再退出
                    IsConfirmExist--;
                };
                if (IsConfirmExist <= 0)
                {
                    MessageToastManager.Show("再按一次返回键将退出漫画岛！", MessageToastLevel.Warn, show, 60);
                    e.Cancel = true;
                }
                else
                {
                }
            }
            else
            {
                this.pivot.SelectedItem = this.pivotStore;
                e.Cancel = true;
            }

            base.OnBackKeyPress(e);
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //欢迎页
            if (!ApplicationSettingHelper.IsExists(KEYS.ASKEY_AppHelpControl))
            {
                ApplicationSettingHelper.Add(KEYS.ASKEY_AppHelpControl, true);
                this.appHelpControl.SetPhoneApplicationPage(this, ComicIslandPage.StartPage);
                this.LayoutRoot.Children.Add(this.appHelpControl);
            }
            //

            SyncLocalToService();
        }

        private bool IsRefreshFocus = false, IsRefreshAlbum = false;
        private double firstY = 0.0;
        private void PhoneApplicationPage_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (firstY == 0.0)
            {
                firstY = e.CumulativeManipulation.Translation.Y;
            }
            else
            {
                if (IsRefreshFocus || IsRefreshAlbum)//正在刷新中
                {
                    MessageToastManager.Show("正在刷新数据！");
                    return;
                }
                double result = e.CumulativeManipulation.Translation.Y - firstY;
                if (result > 0)
                {
                    //this.Dispatcher.BeginInvoke(() =>
                    //{
                    IsRefreshFocus = true;
                    IsRefreshAlbum = true;
                    //向下滑动时重新加载数据                    
                    LoadBookStoreFocus();
                    LoadBookStoreAlbum();
                    //});
                }
                else if (result < 0)
                {
                    //向上滑动时显示不处理
                }
                firstY = 0.0;
            }
            base.OnManipulationDelta(e);
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.pivotStore == this.pivot.SelectedItem)
            {
                ApplicationBar = (ApplicationBar)Resources["appbarPivotStore"];
            }
            else if (this.pivotCategory == this.pivot.SelectedItem)
            {
                if (!IsLoadedCategorySpecial)
                {
                    IsLoadedCategorySpecial = true;
                    this.LoadCategorySpecial();
                }
                ApplicationBar = (ApplicationBar)Resources["appbarPivotCategory"];
            }
            else if (this.pivotBookcase == this.pivot.SelectedItem)
            {
                LoadBookcase();
                ApplicationBar = (ApplicationBar)Resources["appbarPivotBookcase"];
            }
            else if (this.pivotSearch == this.pivot.SelectedItem)
            {
                if (!IsLoaded_SearchChannel_CategoryChoice)
                {
                    IsLoaded_SearchChannel_CategoryChoice = true;
                    SearchChannel_LoadCategoryChoice();
                }
                if (!IsLoaded_SearchChannel_HotSearchword)
                {
                    IsLoaded_SearchChannel_HotSearchword = true;
                    SearchChannel_LoadHotSearchword();
                }
                ApplicationBar = (ApplicationBar)Resources["appbarPivotSearch"];
            }
        }


        private void appBarPersonalCenter_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.PersonalCenterPage);
        }

        private void appBarSearch_Click(object sender, EventArgs e)
        {
            //NaviService.Navigate(ComicIslandPage.SearchPage);
        }



        #region ******************************书城******************************
        #region ********************焦点图********************
        void LoadBookStoreFocus()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/getproad?adgroupid=1&channelid=1&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload && !this.IsRefreshFocus)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonBookStoreFocusBase>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info.JsonString)))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    ObservableCollection<JsonBookStoreFocusAdlistjson> items = JSONHelper.Deserialize<ObservableCollection<JsonBookStoreFocusAdlistjson>>(rootCharacterString.Info.JsonString);
                    BindBookStoreFocus(items);
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonBookStoreFocusBase>(result);
                        if (!(rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info.JsonString)))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            ObservableCollection<JsonBookStoreFocusAdlistjson> items = JSONHelper.Deserialize<ObservableCollection<JsonBookStoreFocusAdlistjson>>(rootCharacterString.Info.JsonString);
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindBookStoreFocus(items);
                            });
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                        this.IsRefreshFocus = false;
                    }
                });
            }, webTask);

        }

        void BindBookStoreFocus(ObservableCollection<JsonBookStoreFocusAdlistjson> itemsource)
        {
            if (!(itemsource != null && itemsource.Count > 0))
                return;
            this.panelBookStoreFocusSelectedIndex.Children.Clear();
            this.panoramaFocus.Items.Clear();
            bool IsSetDefaultedItem = true;
            for (int i = 0; i < itemsource.Count; i++)
            {
                try
                {
                    JsonBookStoreFocusAdlistjson item = itemsource[i];
                    if (item == null)
                        continue;
                    if (string.IsNullOrWhiteSpace(item.Imageurl))
                        continue;
                    //
                    PanoramaItem pi = new PanoramaItem();
                    InterfaceHelper.Targetmethod tm = (InterfaceHelper.Targetmethod)item.Targetmethod;
                    switch (tm)
                    {
                        case InterfaceHelper.Targetmethod.InStation:
                        case InterfaceHelper.Targetmethod.OutStation:
                        case InterfaceHelper.Targetmethod.Download:
                            //Grid grid = new Grid() { Background = new SolidColorBrush(Colors.Red), Tag = item, Margin = new Thickness(-12, -36, 0, 0) };
                            //pi.Content = grid;
                            SurfaceAdControl surfaceAdControl = new SurfaceAdControl();
                            string adToken = "Yg84XTVRYwpiAzhaNUdjCmIR";
                            string adPosition = "55d03605ffc6be964763495bd877286d";
                            surfaceAdControl.AdRefreshInterval = 100;
                            surfaceAdControl.AdToken = adToken;
                            surfaceAdControl.AdPosition = adPosition;
                            surfaceAdControl.IsShowCloseIcon = true;
                            surfaceAdControl.IsEnabledAnimation = false;
                            surfaceAdControl.Margin = new Thickness(-12, -36, 0, 0);
                            pi.Content = surfaceAdControl;
                            surfaceAdControl.InitAdControl(AdModeType.Debug);
                            break;
                        case InterfaceHelper.Targetmethod.BigComic:
                        case InterfaceHelper.Targetmethod.Special:
                        case InterfaceHelper.Targetmethod.Subject:
                            {
                                BitmapImage bmp = new BitmapImage(new Uri(item.Imageurl, UriKind.RelativeOrAbsolute));
                                Image imageFocus = new Image();
                                imageFocus.Tag = item;
                                imageFocus.Source = bmp;
                                imageFocus.Stretch = System.Windows.Media.Stretch.Fill;
                                imageFocus.MouseLeftButtonDown += delegate(object sender, System.Windows.Input.MouseButtonEventArgs e)
                                {
                                    this.StopRefreshTimerFromBookStoreFocus();
                                };
                                imageFocus.MouseLeftButtonUp += delegate(object sender, System.Windows.Input.MouseButtonEventArgs e)
                                {
                                    this.StartRefreshTimerFromBookStoreFocus();
                                };
                                pi.Content = imageFocus;
                            }
                            break;
                    }
                    pi.Tag = item;
                    pi.Tap += PanoramaItemFocus_Tap;
                    //
                    this.panoramaFocus.Items.Add(pi);
                    //
                    TextBlock txt = new TextBlock() { Text = (i + 1).ToString(), FontSize = 20, FontWeight = FontWeights.Normal, Margin = new Thickness(5, 0, 5, 0), FontFamily = new FontFamily("Microsoft Yahei"), VerticalAlignment = System.Windows.VerticalAlignment.Center, HorizontalAlignment = System.Windows.HorizontalAlignment.Center };
                    txt.DataContext = item;
                    txt.Tag = i;
                    if (IsSetDefaultedItem)
                    {
                        IsSetDefaultedItem = false;
                        txt.FontWeight = FontWeights.Normal;
                        txt.FontSize = 30;

                        (this.panoramaFocus.Items[i] as PanoramaItem).Visibility = Visibility.Collapsed;
                        this.panoramaFocus.SetValue(Panorama.SelectedItemProperty, this.panoramaFocus.Items[i]);
                        this.panoramaFocus.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                        (this.panoramaFocus.Items[i] as PanoramaItem).Visibility = Visibility.Visible;
                        //
                        this.currentSelectedItemJsonBookStoreFocusAdlistjson = item;
                        this.txtbBookStoreFocusTitle.Text = item.Title;
                    }
                    this.panelBookStoreFocusSelectedIndex.Children.Add(txt);
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
            //热点：默认选择第一项并开启大图的调度器
            this.StartRefreshTimerFromBookStoreFocus();
        }

        private void StartRefreshTimerFromBookStoreFocus()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    if (this.refreshTimerBookStoreFocus == null)
                    {
                        this.refreshTimerBookStoreFocus = new DispatcherTimer();
                        this.refreshTimerBookStoreFocus.Interval = new TimeSpan(0, 0, TIMER_INTERVAL);
                        this.refreshTimerBookStoreFocus.Tick += adRefreshTimer_Tick;
                    }
                    this.refreshTimerBookStoreFocus.Start();
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                }
            });
        }

        private void StopRefreshTimerFromBookStoreFocus()
        {
            if (this.refreshTimerBookStoreFocus != null)
            {
                this.refreshTimerBookStoreFocus.Stop();
                this.refreshTimerBookStoreFocus = null;
            }
        }

        private void adRefreshTimer_Tick(object sender, object e)
        {
            UpdateCurrentSelectedItem();
        }

        private void UpdateCurrentSelectedItem(Helper.GestureDirection gestureDirection = Helper.GestureDirection.FromLeftToRight)
        {
            this.StopRefreshTimerFromBookStoreFocus();
            if (gestureDirection == ComicIsland.Common.Helper.GestureDirection.FromLeftToRight)
            {
                //右移(下一条)
                if (this.currentSelectedIndexJsonBookStoreFocusAdlistjson < 0)
                    this.currentSelectedIndexJsonBookStoreFocusAdlistjson = 0;
                else
                    this.currentSelectedIndexJsonBookStoreFocusAdlistjson++;
                if (this.currentSelectedIndexJsonBookStoreFocusAdlistjson >= this.panoramaFocus.Items.Count)//重置
                    this.currentSelectedIndexJsonBookStoreFocusAdlistjson = 0;
            }
            else if (gestureDirection == ComicIsland.Common.Helper.GestureDirection.FromRightToLeft)
            {
                //左移（上一条）
                if (this.currentSelectedIndexJsonBookStoreFocusAdlistjson > 0)
                    this.currentSelectedIndexJsonBookStoreFocusAdlistjson--;
                else
                    this.currentSelectedIndexJsonBookStoreFocusAdlistjson = this.panoramaFocus.Items.Count - 1;
            }
            if (this.panoramaFocus.Items != null && this.panoramaFocus.Items.Count > 0)
            {
                try
                {
                    this.currentSelectedItemJsonBookStoreFocusAdlistjson = (this.panoramaFocus.Items[this.currentSelectedIndexJsonBookStoreFocusAdlistjson] as PanoramaItem).Tag as JsonBookStoreFocusAdlistjson;
                    (this.panoramaFocus.Items[this.currentSelectedIndexJsonBookStoreFocusAdlistjson] as PanoramaItem).Visibility = Visibility.Collapsed;
                    this.panoramaFocus.SetValue(Panorama.SelectedItemProperty, this.panoramaFocus.Items[this.currentSelectedIndexJsonBookStoreFocusAdlistjson]);
                    this.panoramaFocus.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                    (this.panoramaFocus.Items[this.currentSelectedIndexJsonBookStoreFocusAdlistjson] as PanoramaItem).Visibility = Visibility.Visible;
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
            this.StartRefreshTimerFromBookStoreFocus();
        }


        private void panoramaFocus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.StopRefreshTimerFromBookStoreFocus();
            try
            {
                this.currentSelectedIndexJsonBookStoreFocusAdlistjson = this.panoramaFocus.SelectedIndex;
                for (int i = 0; i < this.panelBookStoreFocusSelectedIndex.Children.Count; i++)
                {
                    try
                    {
                        TextBlock txt = this.panelBookStoreFocusSelectedIndex.Children[i] as TextBlock;
                        if (txt == null)
                            return;
                        JsonBookStoreFocusAdlistjson item = txt.DataContext as JsonBookStoreFocusAdlistjson;
                        if (item == null)
                            continue;
                        int index = 0;
                        if (txt.Tag != null)
                            int.TryParse(txt.Tag.ToString(), out index);
                        if (index <= 0)
                            index = 0;
                        else if (index >= this.panoramaFocus.Items.Count - 1)
                            index = this.panoramaFocus.Items.Count - 1;
                        if (this.panoramaFocus.SelectedIndex == index)
                        {
                            txt.FontSize = 30;
                            txt.FontWeight = FontWeights.Normal;
                            this.currentSelectedItemJsonBookStoreFocusAdlistjson = item;
                        }
                        else
                        {
                            txt.FontSize = 20;
                            txt.FontWeight = FontWeights.ExtraBold;
                        }
                    }
                    catch (Exception err)
                    {
                        LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }
            if (this.currentSelectedItemJsonBookStoreFocusAdlistjson != null)
                this.txtbBookStoreFocusTitle.Text = this.currentSelectedItemJsonBookStoreFocusAdlistjson.Title;
            this.StartRefreshTimerFromBookStoreFocus();
        }


        void PanoramaItemFocus_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.StopRefreshTimerFromBookStoreFocus();
            try
            {
                this.currentSelectedItemJsonBookStoreFocusAdlistjson = ((sender as PanoramaItem).Tag) as JsonBookStoreFocusAdlistjson;
                if (this.currentSelectedItemJsonBookStoreFocusAdlistjson != null)
                {
                    InterfaceHelper.Targetmethod tm = (InterfaceHelper.Targetmethod)this.currentSelectedItemJsonBookStoreFocusAdlistjson.Targetmethod;
                    switch (tm)
                    {
                        case InterfaceHelper.Targetmethod.BigComic:
                            //NaviService.Navigate(ComicIslandPage.ComicDetailPage, string.Concat("?comicId=", this.currentSelectedItemJsonBookStoreFocusAdlistjson.Targetargument));
                            NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", this.currentSelectedItemJsonBookStoreFocusAdlistjson.Targetargument));
                            break;
                        case InterfaceHelper.Targetmethod.Special:
                            NaviService.Navigate(ComicIslandPage.SpecialListPage,
                                string.Concat("?specialId=", this.currentSelectedItemJsonBookStoreFocusAdlistjson.Targetargument,
                                "&title=", Uri.EscapeDataString(this.currentSelectedItemJsonBookStoreFocusAdlistjson.Title)));
                            break;
                        case InterfaceHelper.Targetmethod.Subject:
                            LogHelper.LogInfo(tm.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            LogHelper.LogInfo(JSONHelper.Serialize<JsonBookStoreFocusAdlistjson>(this.currentSelectedItemJsonBookStoreFocusAdlistjson), this.GetType(), MethodBase.GetCurrentMethod());
                            break;
                        case InterfaceHelper.Targetmethod.InStation:
                            LogHelper.LogInfo(tm.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            LogHelper.LogInfo(JSONHelper.Serialize<JsonBookStoreFocusAdlistjson>(this.currentSelectedItemJsonBookStoreFocusAdlistjson), this.GetType(), MethodBase.GetCurrentMethod());
                            break;
                        case InterfaceHelper.Targetmethod.OutStation:
                            LogHelper.LogInfo(tm.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            LogHelper.LogInfo(JSONHelper.Serialize<JsonBookStoreFocusAdlistjson>(this.currentSelectedItemJsonBookStoreFocusAdlistjson), this.GetType(), MethodBase.GetCurrentMethod());
                            break;
                        case InterfaceHelper.Targetmethod.Download:
                            LogHelper.LogInfo(tm.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            LogHelper.LogInfo(JSONHelper.Serialize<JsonBookStoreFocusAdlistjson>(this.currentSelectedItemJsonBookStoreFocusAdlistjson), this.GetType(), MethodBase.GetCurrentMethod());
                            break;
                        case InterfaceHelper.Targetmethod.None:
                        default:
                            LogHelper.LogInfo(tm.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            LogHelper.LogInfo(JSONHelper.Serialize<JsonBookStoreFocusAdlistjson>(this.currentSelectedItemJsonBookStoreFocusAdlistjson), this.GetType(), MethodBase.GetCurrentMethod());
                            break;
                    }
                    LogHelper.LogInfo(tm.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    //PageNavigationService(string.Format(Keys.KEY_INTERNAL_DETAIL_DETAILINFOPAGE, Helper.GetEncodeUrl(this.currentSelectedItemFromBoutiqueSlideshowBig.TargetClickUrl)));
                }
                else
                {
                    LogHelper.LogInfo("未选中", this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }
            this.StartRefreshTimerFromBookStoreFocus();
        }


        #endregion ********************焦点图********************


        #region ********************栏目列表********************
        void LoadBookStoreAlbum()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/getalbumlist?channelid=1&", KEYS.REQUEST_QUERY_PLATFORM);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload && !this.IsRefreshAlbum)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonBookStoreAlbumBase>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    BindBookStoreAlbum(rootCharacterString.Info);
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonBookStoreAlbumBase>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            BindBookStoreAlbum(rootCharacterString.Info);
                        }

                        #endregion 获取结果处理

                    }
                    catch (Exception err)
                    {
                        MessageToastManager.Show(err.ToString(), MessageToastLevel.Error);
                    }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                        this.IsRefreshAlbum = false;
                    }
                });
            }, webTask);
        }

        void BindBookStoreAlbum(ObservableCollection<JsonBookStoreAlbumInfo> infos)
        {
            if (!(infos != null && infos.Count > 0))
            {
                LogHelper.LogError("书城栏目数据为空！", this.GetType(), MethodBase.GetCurrentMethod());
                return;
            }

            foreach (JsonBookStoreAlbumInfo item in infos)
            {
                var areablocks = JSONHelper.Deserialize<ObservableCollection<JsonBookStoreAlbumInfoAreaBlock>>(item.Bigbooksjson);
                item.Bigbooks = areablocks;
            }
            //1.按item.Id/Name/Targetmethod/Targetargument分组,BookStoreAlbumBindingConverter转换器
            var groupedAlbums =
                from p in infos
                //orderby p.Id
                group p by string.Concat(p.Id, KEYS.SPLITSTRING, p.Name, KEYS.SPLITSTRING, p.Targetmethod, KEYS.SPLITSTRING, p.Targetargument) into AlbumName
                select new AlbumKeyedList<string, JsonBookStoreAlbumInfo>(AlbumName);
            var itemsource = new ObservableCollection<AlbumKeyedList<string, JsonBookStoreAlbumInfo>>(groupedAlbums);
            this.llsBookStoreAlbum.ItemsSource = itemsource;
            //2.绑定不显示Blocks子集?
            //var groupedAlbums1 =
            //    (from p in infos
            //    orderby p.Id
            //    group p by new { p.Id, p.Name, p.Targetargument, p.Targetmethod } into AlbumName
            //    select new { Id = AlbumName.Key.Id, Name = AlbumName.Key.Name, Targetargument = AlbumName.Key.Targetargument, Targetmethod = AlbumName.Key.Targetmethod, Source = new ObservableCollection<JsonBookStoreAlbumInfo>(AlbumName.ToList <JsonBookStoreAlbumInfo>()) }).ToList();
            //ObservableCollection<TMPCLASS> tmpClasses = new ObservableCollection<TMPCLASS>();            
            //foreach (var g in groupedAlbums1)
            //{
            //    TMPCLASS tc = new TMPCLASS() 
            //    {
            //         Id = g.Id,
            //         Name = g.Name,
            //         Targetargument = g.Targetargument,
            //         Targetmethod = g.Targetmethod,
            //         Source = g.Source
            //    };
            //    if (tc.Source != null && tc.Source.Count > 0)
            //    {
            //        tc.Blocks = tc.Source[0].Bigbooks;
            //    }
            //    tmpClasses.Add(tc);
            //}
            //this.llsBookStoreAlbum.ItemsSource = tmpClasses;
        }

        private void lstComicBigBook_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = (sender as ListBox).SelectedItem as JsonBookStoreAlbumInfoAreaBlock;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.Bigbookid));
            }
        }

        /// <summary>
        /// 查看更多
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtbBookStoreAlbumViewMore_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

            try
            {
                string key = (sender as TextBlock).DataContext.ToString();
                LogHelper.LogInfo(key, this.GetType(), MethodBase.GetCurrentMethod());
                if (string.IsNullOrWhiteSpace(key.Trim()))
                    return;
                //p.Id, KEYS.SPLITSTRING, p.Name, KEYS.SPLITSTRING, p.Targetmethod, KEYS.SPLITSTRING, p.Targetargument
                string[] values = Regex.Split(key, KEYS.SPLITSTRING);
                if (values != null && values.Length == 4)
                {
                    int targetMethod = 0, targetArgument = 0;
                    int.TryParse(values[2], out targetMethod);
                    int.TryParse(values[3], out targetArgument);
                    string title = Uri.EscapeDataString(values[1]);
                    LogHelper.LogInfo(string.Concat(targetMethod, "_", targetArgument), this.GetType(), MethodBase.GetCurrentMethod());
                    InterfaceHelper.Targetmethod tm = (InterfaceHelper.Targetmethod)targetMethod;
                    switch (tm)
                    {
                        case InterfaceHelper.Targetmethod.Subject:
                            NaviService.Navigate(ComicIslandPage.SearchFilterPage, string.Concat("?subject=", targetArgument, "&title=", title));
                            break;
                        case InterfaceHelper.Targetmethod.Special:
                            NaviService.Navigate(ComicIslandPage.SpecialListPage, string.Concat("?specialId=", targetArgument, "&title=", title));
                            break;
                        default:
                            break;
                    }
                }
            }
            catch { }
            e.Handled = true;
        }
        #endregion ********************栏目列表********************
        #endregion ******************************书城******************************


        #region ******************************分类中心******************************
        void SetPivotCategoryVisibility(double sujectOpactiyValue, double specialOpactiyValue, double authoOpactiyValue, Visibility sujectVisibilityValue, Visibility specialVisibilityValue, Visibility authorVisibilityValue)
        {
            this.gridPivotCategorySubject.Background.Opacity = sujectOpactiyValue;
            this.gridPivotCategorySpecial.Background.Opacity = specialOpactiyValue;
            this.gridPivotCategoryAuthor.Background.Opacity = authoOpactiyValue;
            this.llsCategorySubject.Visibility = sujectVisibilityValue;
            this.llsCategorySpecial.Visibility = specialVisibilityValue;
            this.llsCategoryAuthor.Visibility = authorVisibilityValue;
        }
        private void gridPivotCategorySubject_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSubjectName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentWhiteColor"])));
            this.txtSpecialName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtAuthorName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            SetPivotCategoryVisibility(1, 0, 0, Visibility.Visible, Visibility.Collapsed, Visibility.Collapsed);
            if (!(this.llsCategorySubject.ItemsSource != null && this.llsCategorySubject.ItemsSource.Count > 0))
                this.LoadCategorySubject();
        }

        private void gridPivotCategorySpecial_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSubjectName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtSpecialName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentWhiteColor"])));
            this.txtAuthorName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            SetPivotCategoryVisibility(0, 1, 0, Visibility.Collapsed, Visibility.Visible, Visibility.Collapsed);
            if (!(this.llsCategorySpecial.ItemsSource != null && this.llsCategorySpecial.ItemsSource.Count > 0))
                this.LoadCategorySpecial();
        }

        private void gridPivotCategoryAuthor_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSubjectName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtSpecialName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
            this.txtAuthorName.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentWhiteColor"])));
            SetPivotCategoryVisibility(0, 0, 1, Visibility.Collapsed, Visibility.Collapsed, Visibility.Visible);
            if (!(this.llsCategoryAuthor.ItemsSource != null && this.llsCategoryAuthor.ItemsSource.Count > 0))
                LoadCategoryAuthor();
        }

        /// <summary>
        /// 按精选分类
        /// </summary>
        void LoadCategorySpecial()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/recommendspecial", "?", KEYS.REQUEST_QUERY_PLATFORM);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCategorySpecial>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Specials != null && rootCharacterString.Info.Specials.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.Specials;
                    BindCategorySpecial(items);
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {

                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCategorySpecial>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Specials != null && rootCharacterString.Info.Specials.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.Specials;
                            if (items != null && items.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindCategorySpecial(items);
                            }
                        }
                        #endregion 获取结果处理

                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindCategorySpecial(ObservableCollection<JsonComicCategorySpecialInfoSpecial> items)
        {
            if (!(items != null && items.Count > 0))
                return;
            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.llsCategorySpecial.ItemsSource != null && this.llsCategorySpecial.ItemsSource.Count > 0)
                {
                    foreach (var item in items)
                    {
                        this.llsCategorySpecial.ItemsSource.Add(item);
                    }
                }
                else
                {
                    this.llsCategorySpecial.ItemsSource = items;
                }
            });
        }

        /// <summary>
        /// 按精选分类
        /// </summary>
        void LoadCategorySubject()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/recommendsubject?channelid=appstore&", KEYS.REQUEST_QUERY_PLATFORM);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCategorySubject>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Subjects != null && rootCharacterString.Info.Subjects.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.Subjects;
                    if (items != null && items.Count > 0)
                    {
                        BindLoadCategorySubject(items);
                    }
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                    {
                        try
                        {

                            #region 获取结果处理
                            string result = webTask.EndWebTask(callBackResult);

                            if (string.IsNullOrWhiteSpace(result))
                            {
                                LogHelper.LogError("Result is empty.");
                                //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                                return;
                            }
                            //
                            if (result.StartsWith("exception:"))
                            {
                                LogHelper.LogError(result);
                                //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                                return;
                            }
                            LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                            //
                            var rootCharacterString = JSONHelper.Deserialize<JsonComicCategorySubject>(result);
                            if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Subjects != null && rootCharacterString.Info.Subjects.Count > 0))
                            {
                                //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                            }
                            else
                            {
                                var items = rootCharacterString.Info.Subjects;
                                if (items != null && items.Count > 0)
                                {
                                    cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                    BindLoadCategorySubject(items);
                                }
                            }

                            #endregion 获取结果处理

                        }
                        catch (Exception err)
                        {

                        }
                        finally
                        {
                            this.psbStore.CloseStatusBar();
                        }
                    });
            }, webTask);
        }

        void BindLoadCategorySubject(ObservableCollection<JsonComicCategorySubjectInfoSubject> items)
        {
            if (!(items != null && items.Count > 0))
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.llsCategorySubject.ItemsSource != null && this.llsCategorySubject.ItemsSource.Count > 0)
                {
                    foreach (var item in items)
                    {
                        this.llsCategorySubject.ItemsSource.Add(item);
                    }
                }
                else
                {
                    this.llsCategorySubject.ItemsSource = items;
                }
            });
        }

        /// <summary>
        /// 按作者分类
        /// </summary>
        void LoadCategoryAuthor()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/recommendauthor_v2", "?", KEYS.REQUEST_QUERY_PLATFORM);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCategoryAuthor>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Authors != null && rootCharacterString.Info.Authors.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.Authors;
                    if (items != null && items.Count > 0)
                    {
                        BindCategoryAuthor(items);
                    }
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCategoryAuthor>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Authors != null && rootCharacterString.Info.Authors.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.Authors;
                            if (items != null && items.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindCategoryAuthor(items);
                            }
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindCategoryAuthor(ObservableCollection<JsonComicCategoryAuthorInfoSubject> items)
        {
            if (!(items != null && items.Count > 0))
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.llsCategoryAuthor.ItemsSource != null && this.llsCategoryAuthor.ItemsSource.Count > 0)
                {
                    foreach (var item in items)
                    {
                        this.llsCategoryAuthor.ItemsSource.Add(item);
                    }
                }
                else
                {
                    this.llsCategoryAuthor.ItemsSource = items;
                }
            });
        }


        private void llsCategorySubject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = this.llsCategorySubject.SelectedItem as JsonComicCategorySubjectInfoSubject;
            if (item == null)
                return;
            NaviService.Navigate(ComicIslandPage.SearchFilterPage, string.Concat("?subject=", item.Subjectid, "&title=", Uri.EscapeDataString(item.Name)));
        }

        private void llsCategorySpecial_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = this.llsCategorySpecial.SelectedItem as JsonComicCategorySpecialInfoSpecial;
            if (item == null)
                return;
            NaviService.Navigate(ComicIslandPage.SpecialListPage, string.Concat("?specialId=", item.Specialid, "&title=", item.Name));
        }

        private void llsCategoryAuthor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = this.llsCategoryAuthor.SelectedItem as JsonComicCategoryAuthorInfoSubject;
            if (item == null)
                return;
            NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(item.Name), "&searchType=", ((int)KEYS.SearchType.Detail).ToString()));
        }

        private object lockllsCategoryAuthor = new object();
        private JsonComicCategoryAuthorInfoSubject currentSelectedItemllsCategoryAuthor;
        private void llsCategoryAuthor_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            lock (lockllsCategoryAuthor)
            {
                try
                {
                    if (e.ItemKind != LongListSelectorItemKind.Item)
                        return;
                    currentSelectedItemllsCategoryAuthor = e.Container.Content as JsonComicCategoryAuthorInfoSubject;
                    int selectedIndex = this.llsCategoryAuthor.ItemsSource.IndexOf(currentSelectedItemllsCategoryAuthor);
                    int total = this.llsCategoryAuthor.ItemsSource.Count;
                    if (total - selectedIndex <= 2)
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            MessageToastManager.Show(AppResources.DataNoMore);
                        });
                    }
                }
                catch { }
            }
        }
        #endregion ******************************分类中心******************************


        #region ******************************搜索栏目******************************
        private void appBarPivotSearch_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.SearchFilterPage, string.Concat("?searchPageNavigateType=", Convert.ToInt32(KEYS.SearchPageNavigateSearchType.None).ToString()));
        }

        #region ********************热门搜索词********************
        void SearchChannel_LoadHotSearchword()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, string.Concat("/comic/hotsearch?e=", DateTime.Now.Ticks, "&", KEYS.REQUEST_QUERY_PLATFORM));
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonSearchHotWord>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.HotWordsList != null && rootCharacterString.Info.HotWordsList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.HotWordsList;
                            if (items != null && items.Count > 0)
                            {
                                this.Dispatcher.BeginInvoke(() =>
                                {
                                    this.wpSearchword.Children.Clear();
                                    foreach (JsonSearchHotWordList item in items)
                                    {
                                        TextBlock txt = new TextBlock();
                                        txt.Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultContentToggleSwitchColor"])));
                                        txt.DataContext = item;
                                        txt.Text = item.Keyword;
                                        txt.Margin = new Thickness(0, 0, 20, 5);
                                        txt.Tap += SearchChannel_HotSearchword_Tap;
                                        this.wpSearchword.Children.Add(txt);
                                    }
                                });
                            }
                        }
                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void SearchChannel_HotSearchword_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                JsonSearchHotWordList hotword = (sender as TextBlock).DataContext as JsonSearchHotWordList;
                if (hotword != null && !string.IsNullOrWhiteSpace(hotword.Keyword))
                {
                    Task.Run(() =>
                    {
                        new LocalHistorySearchWordHelper().Add(new LocalHistorySearchWord() { SearchKeyword = hotword.Keyword });
                    });
                    NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(hotword.Keyword), "&searchType=", hotword.Keywordtype));
                }
            }
            catch { }
        }

        private void imageRefreshSearchword_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SearchChannel_LoadHotSearchword();
        }
        #endregion ********************热门搜索词********************

        #region ********************热门分类********************
        void SearchChannel_LoadCategoryChoice()
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/recommendsubject?channelid=appstore&", KEYS.REQUEST_QUERY_PLATFORM);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCategorySubject>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Subjects != null && rootCharacterString.Info.Subjects.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    var items = rootCharacterString.Info.Subjects;
                    if (items != null && items.Count > 0)
                    {
                        SearchChannel_BindCategoryChoice(items);
                    }
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCategorySubject>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Subjects != null && rootCharacterString.Info.Subjects.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info.Subjects;
                            if (items != null && items.Count > 0)
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                SearchChannel_BindCategoryChoice(items);
                            }
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void SearchChannel_BindCategoryChoice(ObservableCollection<JsonComicCategorySubjectInfoSubject> items)
        {
            if (!(items != null && items.Count > 0))
                return;
            this.Dispatcher.BeginInvoke(() =>
            {
                if (this.llsSearchHotCategory.ItemsSource != null && this.llsSearchHotCategory.ItemsSource.Count > 0)
                {
                    foreach (var item in items)
                    {
                        this.llsSearchHotCategory.ItemsSource.Add(item);
                    }
                }
                else
                {
                    this.llsSearchHotCategory.ItemsSource = items;
                }
            });
        }

        private void llsSearchHotCategory_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            JsonComicCategorySubjectInfoSubject item = this.llsSearchHotCategory.SelectedItem as JsonComicCategorySubjectInfoSubject;
            if (item != null)
            {
                if (item == null)
                    return;
                NaviService.Navigate(ComicIslandPage.SearchFilterPage, string.Concat("?subject=", item.Subjectid, "&title=", Uri.EscapeDataString(item.Name)));
            }
        }
        #endregion ********************热门分类********************

        #region ********************求书********************
        CustomMessageBox messageBoxWantBook = null;
        private void appBarWantBook_Click(object sender, EventArgs e)
        {
            TextBox txtInfo = new TextBox()
            {
                Text = string.Empty
            };
            txtInfo.GotFocus += txtInfo_GotFocus;
            txtInfo.LostFocus += txtInfo_LostFocus;
            TiltEffect.SetIsTiltEnabled(txtInfo, true);
            messageBoxWantBook = new CustomMessageBox()
            {
                VerticalAlignment = System.Windows.VerticalAlignment.Bottom,
                Caption = "搜索不到，我想要",
                Message = string.Concat("搜救不到想要的漫画？不要着急，赶紧“求书”吧！", System.Environment.NewLine, "温馨提示：一定要先搜索看看，搜索不到再来此填写需要的漫画！"),
                Content = txtInfo,
                LeftButtonContent = "确认",
                RightButtonContent = "取消"
            };
            this.messageBoxWantBook.Style = Application.Current.Resources["CustomMessageBoxStyleComic"] as Style;
            messageBoxWantBook.Dismissing += delegate(object senderDismissing, DismissingEventArgs eDismissing)
            {
                if (eDismissing.Result == CustomMessageBoxResult.LeftButton)
                {
                    if (string.IsNullOrWhiteSpace(txtInfo.Text.Trim()))
                    {
                        MessageToastManager.Show("提交内容不能为空！");
                        eDismissing.Cancel = true;
                    }
                }
            };
            messageBoxWantBook.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        LogHelper.LogInfo(txtInfo.Text, this.GetType(), MethodBase.GetCurrentMethod());
                        SearchChannel_WantComic(txtInfo.Text.Trim());
                        break;
                    case CustomMessageBoxResult.RightButton:
                    case CustomMessageBoxResult.None:
                    default:
                        break;
                }
            };

            messageBoxWantBook.Show();
        }



        void txtInfo_LostFocus(object sender, RoutedEventArgs e)
        {
            if (messageBoxWantBook != null)
            {
                messageBoxWantBook.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
            }
        }

        void txtInfo_GotFocus(object sender, RoutedEventArgs e)
        {
            if (messageBoxWantBook != null)
            {
                messageBoxWantBook.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            }
        }

        void SearchChannel_WantComic(string comicName)
        {
            this.psbStore.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/addfeedback", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("content", comicName);
            parameters.Add("mobile", string.Empty);
            parameters.Add("qq", string.Empty);
            parameters.Add("version", KEYS.STORE_VERSION);
            parameters.Add("feedtype", ((int)KEYS.SearchWantComicFeedType.Comic).ToString());

            PostClientHelper proxy = new PostClientHelper(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        if (e.Error != null)
                        {
                            LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }

                        #region 获取结果处理
                        string result = e.Result;

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }

                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonAddFeedBack>(result);
                        if (KEYS.JSON_SUCCESS == rootCharacterString.Code)
                        {
                            LogHelper.LogInfo("提交成功！");
                            MessageToastManager.Show("提交成功！");
                        }
                        else
                        {
                            LogHelper.LogError("提交失败:\t" + rootCharacterString.CodeMsg);
                            MessageToastManager.Show("提交失败，" + rootCharacterString.CodeMsg);
                        }

                        #endregion 获取结果处理
                    }
                    catch { }
                    finally
                    {
                        this.psbStore.CloseStatusBar();
                    }

                });
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }
        #endregion ********************求书********************

        #region ********************按搜索词进行搜索********************
        private void txtSearchword_GotFocus(object sender, RoutedEventArgs e)
        {
            this.ApplicationBar.IsVisible = false;
            var items = new LocalHistorySearchWordHelper().GetAll();
            if (items != null && items.Count > 0)
            {
                this.llsHistorySearchword.ItemsSource = items;
                if (!this.popupHistoryKeyword.IsOpen)
                {
                    this.popupHistoryKeyword.IsOpen = true;
                }
            }
            //
            this.txtSearchKeyword.Background = new SolidColorBrush(Colors.White);
            if (AppResources.InputComicOrAuthorName.Equals(this.txtSearchKeyword.Text.Trim()))
            {
                this.txtSearchKeyword.Text = string.Empty;
            }
        }
        private void txtSearchword_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //回车
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                //NaviService.Navigate(ComicIslandPage.SearchPage, string.Concat("?searchPageNavigateType=", Convert.ToInt32(KEYS.SearchPageNavigateSearchType.Keyword).ToString(), "&searchKeyword=", Uri.EscapeDataString(this.txtSearchKeyword.Text.Trim())));
                string searchKeyword = this.txtSearchKeyword.Text.ToString();
                if (!string.IsNullOrWhiteSpace(searchKeyword) && !searchKeyword.Equals(AppResources.InputComicOrAuthorName))
                {
                    Task.Run(() =>
                    {
                        new LocalHistorySearchWordHelper().Add(new LocalHistorySearchWord() { SearchKeyword = searchKeyword });
                    });
                    NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(searchKeyword), "&searchType=", ((int)KEYS.SearchType.Detail).ToString()));
                }
            }
        }

        private void txtSearchword_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtSearchKeyword.Text.Trim()))
            {
                this.txtSearchKeyword.Text = AppResources.InputComicOrAuthorName;
            }
        }

        private void imagePivotSearchClearSearchKeyword_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.txtSearchKeyword.Text = AppResources.InputComicOrAuthorName;
        }

        private void imagePivotSearchConfirm_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string searchKeyword = this.txtSearchKeyword.Text.ToString();
            if (!string.IsNullOrWhiteSpace(searchKeyword) && !searchKeyword.Equals(AppResources.InputComicOrAuthorName))
            {
                Task.Run(() =>
                {
                    new LocalHistorySearchWordHelper().Add(new LocalHistorySearchWord() { SearchKeyword = searchKeyword });
                });
                NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(searchKeyword), "&searchType=", ((int)KEYS.SearchType.Detail).ToString()));
            }
        }

        private void txtCleanHistoryWord_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            new LocalHistorySearchWordHelper().Remove();
            if (this.popupHistoryKeyword.IsOpen)
            {
                this.llsHistorySearchword.ItemsSource = null;
                this.popupHistoryKeyword.IsOpen = false;
            }
        }

        private void imageClosePopupHistoryKeyword_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.ApplicationBar.IsVisible = true;
            this.popupHistoryKeyword.IsOpen = false;
        }

        private void gridHistorySearchword_Tab(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LocalHistorySearchWord item = (sender as Grid).DataContext as LocalHistorySearchWord;
            if (item != null && !string.IsNullOrWhiteSpace(item.SearchKeyword))
            {
                NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(item.SearchKeyword), "&searchType=", ((int)KEYS.SearchType.Detail).ToString()));
            }
        }
        #endregion ********************按搜索词进行搜索********************
        #endregion ******************************搜索栏目******************************


        #region ******************************书架栏目******************************
        private void appBarPivotBookcaseSearch_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.SearchFilterPage, string.Concat("?searchPageNavigateType=", Convert.ToInt32(KEYS.SearchPageNavigateSearchType.None).ToString()));
        }

        #region ********************空书架********************
        private void imageBookcaseEmptyBookStoreFind_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.pivot.SelectedItem = this.pivotStore;
        }

        private void imageBookcaseEmptyCategoryFind_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.pivot.SelectedItem = this.pivotCategory;
        }

        private void imageBookcaseEmptySearchFind_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.pivot.SelectedItem = this.pivotSearch;
        }

        /// <summary>
        /// 大家都在看
        /// </summary>
        void LoadBookcaseEmpty()
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/gltj_v2", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();//不提交参数
            PostClientHelper proxy = new PostClientHelper(parameters);
            //
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(string.Concat(requestUrl, proxy.PostData.ToString())));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicRelationRecom>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.TopBigBooks != null && rootCharacterString.Info.TopBigBooks.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.llsBookcaseHasEmpty.ItemsSource = rootCharacterString.Info.TopBigBooks;
                }
                this.psbStore.CloseStatusBar();
                return;
            }

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        return;
                    }

                    #region 获取结果处理
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        LogHelper.LogError("Result is empty.");
                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                        return;
                    }
                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonComicRelationRecom>(result);
                    if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.TopBigBooks != null && rootCharacterString.Info.TopBigBooks.Count > 0))
                    {
                        //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                    }
                    else
                    {
                        cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                        this.llsBookcaseHasEmpty.ItemsSource = rootCharacterString.Info.TopBigBooks;
                    }

                    #endregion 获取结果处理
                }
                catch (Exception err)
                {
                }
                finally
                {
                    this.psbStore.CloseStatusBar();
                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }
        #endregion ********************空书架********************

        #region ********************有书书架********************
        void LoadBookcase()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                var items = new LocalBookcaseInfoHelper().GetAll(new List<LocalBookcaseStatus>() { LocalBookcaseStatus.Add, LocalBookcaseStatus.Update });
                if (items != null && items.Count > 0)
                {
                    this.gridBookcaseHasEmpty.Visibility = System.Windows.Visibility.Collapsed;
                    this.gridBookcaseHasCache.Visibility = System.Windows.Visibility.Visible;
                    items.Insert(0, new LocalBookcaseInfo() { IsAd = true });
                    this.llsBookcaseHasCache.ItemsSource = items;
                }
                else
                {
                    this.gridBookcaseHasEmpty.Visibility = System.Windows.Visibility.Visible;
                    this.gridBookcaseHasCache.Visibility = System.Windows.Visibility.Collapsed;
                    if (!IsLoaded_BookcaseChannel_Empty && IsNeedLoadBookcase)
                    {
                        IsLoaded_BookcaseChannel_Empty = true;
                        this.LoadBookcaseEmpty();
                    }
                }
            });
        }
        #endregion ********************有书书架********************

        private void miBookcaseHasCache_Click(object sender, RoutedEventArgs e)
        {
            var item = (sender as MenuItem).DataContext as LocalBookcaseInfo;
            if (item == null)
                return;
            //收藏夹漫画删除
            Task.Run(() =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    LocalBookcaseInfoHelper helper = new LocalBookcaseInfoHelper();
                    var bookcaseInfo = helper.Get(item.ComicId);
                    if (bookcaseInfo != null)
                    {
                        bookcaseInfo.IsSync = false;
                        bookcaseInfo.Status = LocalBookcaseStatus.Delete.ToString();
                        bookcaseInfo.LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD);
                        if (new LocalBookcaseInfoHelper().Update(bookcaseInfo))
                        {
                            this.LoadBookcase();
                            new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Deleted, bookcaseInfo);
                        }
                    }
                });
            });
        }

        private void appBarCommunity_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.CommunityPage);
        }

        private void llsGridBookcaseHasEmpty_Tab(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Grid grid = (sender as Grid);
            if (grid == null)
                return;
            var item = grid.DataContext as TopBigBook;
            if (item == null)
                return;
            NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.BigbookId));
        }

        private void llsGridBookcaseHasCache_Tab(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Grid grid = (sender as Grid);
            if (grid == null)
                return;
            var item = grid.DataContext as LocalBookcaseInfo;
            if (item == null)
                return;
            Task.Run(() =>
            {
                new LocalBookcaseInfoHelper().UpdateChapterUpdateFlag(new ObservableCollection<LocalBookcaseInfo>() { item }, false);
            });
            NaviService.Navigate(ComicIslandPage.ComicSummaryPage, string.Concat("?comicId=", item.ComicId));
        }
        #endregion ******************************书架栏目******************************


        #region ******************************加载热点漫画******************************
        /// <summary>
        /// 加载热点漫画
        /// <para>每次启动应用都刷新一次</para>
        /// </summary>
        void LoadHotComic()
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicslist_v2", "?", KEYS.REQUEST_QUERY_PLATFORM);

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("sort", 0);
            parameters.Add("pageno", 0);
            parameters.Add("pagesize", 10);
            PostClientHelper proxy = new PostClientHelper(parameters);
            LogHelper.LogInfo(requestUrl + "\t" + proxy.PostData.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            //            
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    if (e.Error != null)
                    {
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        return;
                    }

                    #region 获取结果处理
                    string result = e.Result;

                    if (string.IsNullOrWhiteSpace(result))
                    {
                        LogHelper.LogError("Result is empty.");
                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                        return;
                    }
                    //
                    if (result.StartsWith("exception:"))
                    {
                        LogHelper.LogError(result);
                        //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                        return;
                    }
                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                    //
                    if (result.IndexOf("\"comicsList\":{}") >= 0)
                    {
                        return;
                    }
                    //
                    var rootCharacterString = JSONHelper.Deserialize<JsonChannelMoreBase>(result);
                    if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.ComicsList != null && rootCharacterString.Info.ComicsList.Count > 0))
                    {
                        //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                    }
                    else
                    {
                        var items = rootCharacterString.Info.ComicsList;
                        if (items != null && items.Count > 0)
                        {
                            IsolatedStorageHelper.Instance.WriteText(result, KEYS.KEY_CacheJsonHotComic, true);
                        }
                    }
                    #endregion 获取结果处理
                }
                catch (Exception err)
                {
                }
                finally
                {
                }
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }
        #endregion ******************************加载热点漫画******************************


        #region ******************************收藏夹同步******************************
        /// <summary>
        /// 本地未同步数据同步至服务器
        /// </summary>
        void SyncLocalToService()
        {
            //if (!NetworkStatusHelper.IsNetworkAvailable)
            //{
            //    LogHelper.LogInfo("无网络，不进行操作！");
            //    return;
            //}
            Task.Run(() =>
            {
                DeviceNetworkInfo networkInfo = new NetworkStatusHelper().GetNetworkTypeAsync("http://www.baidu.com").Result;
                if (networkInfo.CustomerNetworkType == DeviceNetworkType.None)
                {
                    LogHelper.LogError("未连接网络，不执行！", this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }
                if (networkInfo.CustomerNetworkType != DeviceNetworkType.Wifi)
                {
                    LogHelper.LogError("未连接WiFi网络，不执行！", this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }
                try
                {
                    LocalBookcaseInfoHelper bookcaseInfoHelper = new LocalBookcaseInfoHelper();
                    //获取未同步的指定状态数据
                    var addItems = bookcaseInfoHelper.GetAll(new List<LocalBookcaseStatus>() { LocalBookcaseStatus.Add }, false);
                    var deletedItems = bookcaseInfoHelper.GetAll(new List<LocalBookcaseStatus>() { LocalBookcaseStatus.Delete }, false);
                    //（未同步的本地添加数据）
                    if (addItems != null && addItems.Count > 0)
                    {
                        foreach (var item in addItems)
                        {
                            try
                            {
                                new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Add, item);
                            }
                            catch { }
                        }
                    }
                    //（未同步的本地删除数据）
                    if (deletedItems != null && deletedItems.Count > 0)
                    {
                        foreach (var item in deletedItems)
                        {
                            try
                            {
                                new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Deleted, item);
                            }
                            catch { }
                        }
                    }
                }
                catch { }
            });
        }

        void GetComicsUpdateInfo()
        {
            LocalBookcaseInfoHelper bookcaseInfoHelper = new LocalBookcaseInfoHelper();
            var items = bookcaseInfoHelper.GetAll(new List<LocalBookcaseStatus>() { LocalBookcaseStatus.Add, LocalBookcaseStatus.Update });
            if (!(items != null && items.Count > 0))
            {
                return;
            }
            //

            //
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicsupdateinfo", "?", KEYS.REQUEST_QUERY_PLATFORM);
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            StringBuilder parametersJson = new StringBuilder();
            for (int i = 0; i < items.Count; i++)
            {
                var item = items[i];
                if (item == null)
                    continue;
                //TODO 测试数据，
                item.LocalUpdateDate = "2015-01-01";
                //
                string json = string.Concat("{\"updatetime\":\"", item.LocalUpdateDate, "\",\"bookid\":\"", item.BookId, "\"}");
                if (i < items.Count - 1)
                {
                    parametersJson.Append(json).Append(",");
                }
                else
                {
                    parametersJson.Append(json);
                }
            }
            parameters.Add(PostFormat.DirectArray.ToString(), parametersJson.ToString());
            PostClientHelper proxy = new PostClientHelper(parameters, PostFormat.DirectArray);
            LogHelper.LogInfo("PostData" + proxy.PostData.ToString());
            LogHelper.LogInfo(requestUrl + "\t" + proxy.PostData.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        if (e.Error != null)
                        {
                            LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }

                        #region ********************获取结果处理********************
                        string result = e.Result;

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicUpdateInfo>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Books != null && rootCharacterString.Info.Books.Count > 0))
                        {
                            LogHelper.LogError("返回结果为空！");
                        }
                        else
                        {
                            if (rootCharacterString.Code == 200)
                            {
                                ObservableCollection<LocalBookcaseInfo> updateBookcases = new ObservableCollection<LocalBookcaseInfo>();
                                foreach (var item in rootCharacterString.Info.Books)
                                {
                                    updateBookcases.Add(new LocalBookcaseInfo() { BookId = item.Bookid, ComicTitle = item.Bookname });
                                }
                                if (updateBookcases != null && updateBookcases.Count > 0)
                                {
                                    //TODO 更新本地书架
                                    new LocalBookcaseInfoHelper().UpdateChapterUpdateFlag(updateBookcases, true);
                                    this.LoadBookcase();
                                }
                            }
                        }
                        #endregion ********************获取结果处理********************
                    }
                    catch
                    {

                    }
                });
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }
        #endregion ******************************收藏夹同步******************************


        #region ******************************Push Notification******************************
        /// <summary>
        /// Push Notification
        /// </summary>
        private void InitPushNotificationChannel()
        {
            try
            {
                HttpNotificationChannel pushChannel;
                string channelName = string.Concat("ComicIslandPushWindowsPhone");
                pushChannel = HttpNotificationChannel.Find(channelName);
                //存在则直接使用，不存在则创建
                if (pushChannel == null)
                {
                    pushChannel = new HttpNotificationChannel(channelName);
                    if (pushChannel == null)
                    {
                        //无法创建实例则不处推送
                        UmengSDK.UmengAnalytics.TrackError(string.Format("new HttpNotificationChannel({0})时出错了！", channelName));
                        return;
                    }
                    pushChannel.ChannelUriUpdated += pushChannel_ChannelUriUpdated;
                    pushChannel.ErrorOccurred += pushChannel_ErrorOccurred;
                    //toast 推送通知服务事件
                    pushChannel.ShellToastNotificationReceived += pushChannel_ShellToastNotificationReceived;

                    pushChannel.Open();

                    //绑定toast 推送服务
                    pushChannel.BindToShellToast();

                    //绑定Tokens (tile) 推送服务 
                    pushChannel.BindToShellTile();
                }
                else
                {
                    pushChannel.ChannelUriUpdated += pushChannel_ChannelUriUpdated;
                    pushChannel.ErrorOccurred += pushChannel_ErrorOccurred;
                    LogHelper.LogInfo(String.Format("Channel Uri is {0}", pushChannel.ChannelUri.ToString()));
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                UmengSDK.UmengAnalytics.TrackError("InitPushNotificationChannel方法异常：" + err.ToString());
            }
        }

        void pushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            LocalAppConfigInfo appConfigInfo = new LocalAppConfigInfoHelper().Get();
            bool isAcceptToast = true;
            if (appConfigInfo != null && appConfigInfo.IsPush == (int)KEYS.PushToastSwitch.Close)
            {
                isAcceptToast = false;
            }
            if (!isAcceptToast)
            {
                //用户不接受推送通知
                return;
            }
            StringBuilder message = new StringBuilder();
            string targetUri = string.Empty;
            //message.AppendFormat("收到 Toast {0}:\n", DateTime.Now.ToShortTimeString());
            foreach (string key in e.Collection.Keys)
            {
                if (key.ToLower() == "wp:param")
                    targetUri = e.Collection[key];
                else
                    message.AppendFormat("{0}{1}", e.Collection[key], Environment.NewLine);
            }
            Dispatcher.BeginInvoke(() =>
            {
                if (string.IsNullOrWhiteSpace(message.ToString()))
                {
                    return;
                }
                if (MessageBoxResult.OK == MessageBox.Show(message.ToString(), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
                {
                    if (!string.IsNullOrWhiteSpace(targetUri))
                    {
                        //TODO pushChannel_ShellToastNotificationReceived 导航至指定页面
                        LogHelper.LogInfo("导航至指定页面......");
                        //Helper.PageNavigationService(targetUri);
                    }
                }
            });
        }

        /// <summary>
        /// Event handler for when the Push Channel Uri changes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            try
            {
                if (e.ChannelUri == null)
                {
                    LogHelper.LogError("未获取到推送地址！", this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }
                //
                WinPhoneDataUpdateHelper updateHelper = new WinPhoneDataUpdateHelper();
                updateHelper.OnWinPhoneDataUpdateResult += updateHelper_OnWinPhoneDataUpdateResult;
                LocalAppConfigInfo appConfigInfo = new LocalAppConfigInfoHelper().Get();
                if (appConfigInfo != null && appConfigInfo.WpId > 0)
                {
                    //更新推送地址
                    if (!appConfigInfo.PushChannelUrl.Equals(e.ChannelUri.ToString()))
                    {
                        appConfigInfo.PushChannelUrl = e.ChannelUri.ToString();
                        //更新推送地址                                              
                        updateHelper.InvokeInterface(KEYS.WpDataUpdateType.updateChannelurl, appConfigInfo);
                    }
                }
                else
                {
                    //首次提交
                    appConfigInfo = new LocalAppConfigInfo();
                    appConfigInfo.SyncData = DateTime.Now.ToString("yyyy-MM-dd");
                    appConfigInfo.PushChannelUrl = e.ChannelUri.ToString();
                    appConfigInfo.IsPush = (int)KEYS.PushToastSwitch.Open;
                    //同步数据
                    updateHelper.InvokeInterface(KEYS.WpDataUpdateType.sync, appConfigInfo);
                }

            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        void updateHelper_OnWinPhoneDataUpdateResult(KEYS.WpDataUpdateType updateType, bool result, string message)
        {
            LogHelper.LogInfo(string.Concat(updateType.ToString(), Environment.NewLine, result, Environment.NewLine, message), this.GetType(), MethodBase.GetCurrentMethod());
        }




        /// <summary>
        /// Event handler for when a Push Notification error occurs.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            // Error handling logic for your particular application would be here.    
            string errorMessage = string.Format("A push notification {0} error occurred.  {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData);
            LogHelper.LogError(errorMessage);
            UmengSDK.UmengAnalytics.TrackError(errorMessage);
        }
        #endregion ******************************Push Notification******************************


        #region ******************************书架广告******************************
        private void llsBookcaseHasCache_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void dtGridSurfaceAdBookcase_Loaded(object sender, RoutedEventArgs e)
        {
            var surfaceAdControls = Helper.FindChildren<SurfaceAdControl>(this.llsBookcaseHasCache);
            if (surfaceAdControls != null && surfaceAdControls.Count() == 1)
            {
                var surfaceAdControl = surfaceAdControls.FirstOrDefault<SurfaceAdControl>();
                if (surfaceAdControl != null)
                {
                    surfaceAdControl.InitAdControl(AdModeType.Debug);
                }
            }
        }
        #endregion ******************************书架广告******************************


        #region ******************************帮助******************************
        public AppHelpControl appHelpControl = new AppHelpControl();
        public void RemoveHelp()
        {
            if (this.LayoutRoot.Children.IndexOf(this.appHelpControl) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.appHelpControl);
            }
        }
        #endregion  ******************************帮助******************************






















        private void gridtr_lstSmallImages_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //var item = this.gridStoreChannelId3.SelectedItem as JsonBookStoreAlbumInfoAreaBlock;
            //if (item != null)
            //{
            //    NaviService.Navigate(ComicIslandPage.ComicDetailPage, string.Concat("?comicId=", item.Bigbookid));
            //}
        }

        private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            JsonBookStoreAlbumInfo item = (sender as TextBlock).Tag as JsonBookStoreAlbumInfo;
            if (item == null)
                return;

            NaviService.Navigate(ComicIslandPage.BookStoreChannelMorePage, string.Concat("?subjectId=", item.Id.ToString()));
        }
















































    }

}
